package com.tanhua.server.service;

import com.tanhua.autoconfig.template.AipFaceTemplate;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.JwtUtils;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.db.User;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.server.exception.BusinessException;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * springboot项目
 */
@Service
public class UserService {

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Autowired
    private MqMessageService mqMessageService;

    //
//    public User findByMobile(String mobile) {
//        return userApi.findByMobile(mobile);
//    }

    //用户登录
    public Map loginVerification(String phone, String verificationCode) {
        //1、获取redis中的验证码
        String code = redisTemplate.opsForValue().get("CODE_"+phone);
        //2、判断验证码是否一致
        if(StringUtils.isEmpty(code) || !code.equals(verificationCode)) {
            //3、如果不一致，抛出异常（返回500错误）
            ErrorResult result = ErrorResult.loginError();
            throw new BusinessException(result);
        }
        //4、如果一致，删除redis中的验证码
        redisTemplate.delete("CODE_"+phone);
        //5、根据手机号码查询用户
        User user = userApi.findByMobile(phone);
        //6、判断用户是否存在，如果不存在，保存
        boolean isNew = false;
        if(user == null) {
            user = new User();
            user.setMobile(phone);
            user.setPassword("123456");
            Long id = userApi.save(user);
            user.setId(id);
            isNew = true;
            //新用户，将用户信息注册到环信
            huanXinTemplate.createUser("hx"+id,"123456"); //用户名=hx+id ，密码=123456
            //更新用户信息，更新hx_user ,hx_password
            user.setHxUser("hx"+id);
            user.setHxPassword("123456");
            userApi.update(user);
        }

        //发送RabbitMQ的消息
//        try {
//            Map<String,String> map = new HashMap<>();
//            map.put("userId",user.getId().toString());
//            map.put("type",isNew?"0102":"0101");
//            map.put("logTime",new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
//            map.put("busId",null); //登录注册不用，业务id
//            String msg = JSON.toJSONString(map);
//            rabbitTemplate.convertAndSend(
//                    "tanhua.log.exchange","log.user",msg);
//        } catch (AmqpException e) {
//            e.printStackTrace();
//        }

        mqMessageService.sendLogMessage(user.getId(),
                isNew?"0102":"0101","user",null);

        //7、生成token(id,手机号码)
        Map tokeMap = new HashMap();
        tokeMap.put("id",user.getId());
        tokeMap.put("mobile",user.getMobile());
        String token = JwtUtils.getToken(tokeMap);
        //8、返回
        Map retMap = new HashMap();
        retMap.put("token",token);
        retMap.put("isNew",isNew);
        return retMap;
    }



    //保存
    public void saveUserInfo(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }



    //更新用户头像
    public void updateHead(Long userId, MultipartFile headPhoto) throws IOException {
        //1、上传到阿里云oss,获取url访问路径
        String avatar = ossTemplate.upload(headPhoto.getOriginalFilename(),
                headPhoto.getInputStream());
        //2、调用工具类，判断是否包含人脸
        boolean detect = aipFaceTemplate.detect(avatar);
        //2.1 如果不包含，抛出异常
        if(!detect) {
            throw new BusinessException(ErrorResult.faceError());
            //throw new RuntimeException("图片中没有人脸");
        }
        //2.2 如果包含，更新
        //如何更新，mybatis-plus更新是可选列更新
        UserInfo userInfo = new UserInfo();
        userInfo.setId(userId);
        userInfo.setAvatar(avatar);
        userInfoApi.update(userInfo);
    }
}
